import React from "react";
import { Modal, Form, Input, Select } from "antd";

import { usePageContext } from "../hooks/useContext";
import { useForm } from "../hooks/useForm";
import { useCreate } from "../hooks/useCreate";
import { useUpdate } from "../hooks/useUpdate";

const FormModal = ({ roles, form }) => {
  const { handleClose } = useForm();
  const {
    state: {
      modalOpen,
      form: { isEdit, handleSubmit }
    }
  } = usePageContext();
  useCreate({ form });
  useUpdate({ form });

  const { getFieldDecorator } = form;
  const prefixSelector = getFieldDecorator("prefix", {
    initialValue: "86"
  })(
    <Select style={{ width: 70 }}>
      <Select.Option value="86">+86</Select.Option>
    </Select>
  );

  return (
    <Modal
      title={isEdit ? "编辑用户" : "新建用户"}
      centered
      visible={modalOpen}
      onOk={handleSubmit}
      onCancel={handleClose}
      okText="确认"
      cancelText="取消"
    >
      <Form layout="vertical">
        <Form.Item label="用户名">
          {getFieldDecorator("username", {
            rules: [{ required: true, message: "请输入用户名！" }]
          })(<Input placeholder="输入用户名..." disabled={isEdit} />)}
        </Form.Item>
        <Form.Item label="邮箱">
          {getFieldDecorator("email", {
            rules: [
              { required: true, message: "请输入邮箱地址！" },
              { type: "email", message: "请输入规范的邮箱地址！" }
            ]
          })(<Input placeholder="输入邮箱地址..." />)}
        </Form.Item>
        <Form.Item label="手机号">
          {getFieldDecorator("mobile", {
            rules: [{ required: true, message: "请输入手机号！" }]
          })(
            <Input addonBefore={prefixSelector} placeholder="输入手机号..." />
          )}
        </Form.Item>
        <Form.Item label="角色">
          {getFieldDecorator("roleIds", {
            rules: [
              { required: true, message: "请至少选择一个角色！", type: "array" }
            ]
          })(
            <Select mode="multiple" placeholder="选择角色...">
              {roles.map(item => (
                <Select.Option key={item.id} value={item.id}>
                  {item.description}
                </Select.Option>
              ))}
            </Select>
          )}
        </Form.Item>
      </Form>
    </Modal>
  );
};

const WrappedForm = Form.create({ name: "modal" })(FormModal);

export default WrappedForm;
